package com.oa.kq.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.Tips;
import com.mdp.core.service.BaseService;
import com.mdp.core.service.SequenceService;
import com.mdp.core.utils.DateUtils;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.oa.kq.entity.*;
import com.oa.kq.mapper.AttendanceMapper;
import com.oa.kq.util.LngLatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月9日
 */
@Service
public class AttendanceService extends BaseService<AttendanceMapper, Attendance> {
    static Logger logger = LoggerFactory.getLogger(AttendanceService.class);

    /**
     * 自定义查询，支持多表关联
     *
     * @param page 分页条件
     * @param ew   一定要，并且必须加@Param("ew")注解
     * @param ext  如果xml中需要根据某些值进行特殊处理，可以通过这个进行传递，非必须，注解也可以不加
     * @return
     */
    public List<Map<String, Object>> selectListMapByWhere(IPage page, QueryWrapper ew, Map<String, Object> ext) {
        return baseMapper.selectListMapByWhere(page, ew, ext);
    }

    @Autowired
    private SequenceService seqService;
    @Autowired
    private GroupScheduleCycleService groupScheduleCycleService;
    @Autowired
    private GroupService groupService;
    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private GroupWifiService groupWifiService;


    // 根据userid获取用户的考勤打卡记录，按时间排序
    public Map<String, Object> getAllAttendance(Date date, User user) {
        Map<String, Object> map = new HashMap<String, Object>();

        Attendance attendance = new Attendance();
        attendance.setUserid(user.getUserid());
        attendance.setWorkTime(date);

        List<Attendance> allAttendance = baseMapper.selectDayAttendance(attendance);
        // 获取打卡记录
        map.put("allAttendance", allAttendance);
        // 打卡次数
        map.put("num", allAttendance.size());
        // 获取今日工时
        Map<String, Object> todayCount = this.getTodayCount(attendance);
        map.put("tHour", todayCount.get("hour"));
        map.put("tMin", todayCount.get("min"));

        // bottomState:打卡按钮的状态，如果最后一条记录是上班，那么按钮为下班
        if (allAttendance != null && allAttendance.size() > 0) {
            if ("0".equals(allAttendance.get(allAttendance.size() - 1).getState())) {
                map.put("bottomState", 0);
            } else if ("1".equals(allAttendance.get(allAttendance.size() - 1).getState())) {
                map.put("bottomState", 1);
            }
        } else {
            map.put("bottomState", -1);
        }

        // 获取用户id
        map.put("userid", user.getUserid());
        // 获取用户名
        map.put("username", user.getUsername());
        // 获取用户头像
        map.put("headimg", user.getHeadimgurl());
        return map;
    }


    /**
     * 插入记录
     *
     * @param attendance
     * @return
     * @判断如果传递的groupid是有值的就是更新不是新增操作
     * @cdate 2020/1/10 11:19
     * @cauthor 林钰坤
     */
    public Map<String, Object> insertAttendance(Attendance attendance, String btnPoi, String deptid) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Tips tips = new Tips();
        User user = LoginUtils.getCurrentUserInfo();
        user.setDeptid(deptid);
        if (user != null && !StringUtils.isEmpty(user.getUserid())) {// 用户编号为空才为空，
            // by
            // chenyc
            // 20170320
            Boolean isInsertFlag = false;
            if (StringUtils.isEmpty(attendance.getId())) {
                isInsertFlag = true;
                attendance.setId(seqService.getTablePK("attendance", "id"));
            }
            attendance.setUserid(user.getUserid());
            if (ObjectUtils.isEmpty(attendance.getWorkTime())) {
                attendance.setWorkTime(DateUtils.getNowDate());
            }
            if (btnPoi.equals("-1")) {//表示没有定位 不传递坐标位置，永远都是正常打卡
                attendance.setOntimeState("0");
            } else {
                //判断当前打卡状态：正常旷工等。
                attendance.setOntimeState(getOntimeState(user, attendance, btnPoi, deptid) + "");
            }
            if (isInsertFlag) {
                this.insert(attendance);
            } else {
                this.updateSomeFieldByPk(attendance);
            }

            map.put("attendance", attendance);
            map.put("tips", tips);

        } else {
            tips.setErrMsg("用户未注册，无法签到！");
            map.put("tips", tips);
        }

        return map;
    }

    public boolean isHere(Attendance attendance, String bssid, String deptid) {
        // 判断对方是否在公司,限度100米范围。否则不允许打卡
        // 公司经纬度 lat=23.026604 lng=113.31965
        // 113.3155187874952
        // 上海39.984154,116.307490：测试不在公司
        double compLat = 23.026604;
        //double compLng = 113.31965;
        double compLng = 113.31551;
        double userLat;
        double userLng;
        try {
            userLat = Double.parseDouble(attendance.getWorkLatitude());
            userLng = Double.parseDouble(attendance.getWorkLongitude());
            int effectiveRange = 500;


            User user = LoginUtils.getCurrentUserInfo();
            user.setDeptid(deptid);

            if (user != null && !StringUtils.isEmpty(user.getUserid())) {
                Group group = groupService.selectGroupByUseridAndDeptid(user.getUserid(), user.getDeptid());
                if (group != null) {
                    if (!StringUtils.isEmpty(group.getEffectiveRange())) {
                        effectiveRange = Integer.parseInt(group.getEffectiveRange());//考勤范围
                    }
                    if (!StringUtils.isEmpty(bssid)) {
                        GroupWifi gw = new GroupWifi();
                        gw.setGroupId(group.getId());
                        gw.setBssid(bssid);
                        if (!CollectionUtils.isEmpty(groupWifiService.selectListByWhere(gw))) {
                            return true;
                        }
                        ;
                    }
                }
            }

            if (LngLatUtils.getDistance(userLat, userLng, compLat, compLng) <= effectiveRange) {
                return true;
            } else {
                return false;
            }
        } catch (NumberFormatException e) {// 客户端可能上传了特殊字符上来，需要做异常处理， by chenyc
            // 20170320
            return false;
        }

    }

    /**
     * 个人统计：计算某月总工时/平均工时/出勤天数/正常打卡天数
     *
     * @param month
     * @return
     */
    public Map<String, Object> getThisMonthCount(String month) {
        // String month :2017-03
        Map<String, Object> map = new HashMap<String, Object>();
        long mHour = 0;
        long mMin = 0;
        int days = 0;// 出勤天数
        int normal = 0;// 正常打卡天数

        // 获取用户信息
        Attendance attendance = new Attendance();
        User user = LoginUtils.getCurrentUserInfo();
        attendance.setUserid(user.getUserid());
        // 获取今天的日期
        Calendar ca = Calendar.getInstance();
        int day;
        String[] split = month.split("-");
        // 如果不是当前月
        if (Integer.parseInt(split[0]) != ca.get(Calendar.MONTH + 1)) {
            ca.set(Calendar.YEAR, Integer.parseInt(split[0]));
            ca.set(Calendar.MONTH, Integer.parseInt(split[1]) - 1);// Java月份才0开始算
            day = ca.getActualMaximum(Calendar.DATE);
        } else {
            day = ca.get(Calendar.DATE);// 获取日
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date today;
        int count = day;
        for (int i = 0; i < count; i++) {
            // 循环取出每个月的每一个的工时
            try {
                today = sdf.parse(month + "-" + day);
                attendance.setWorkTime(today);
                Map<String, Object> todayCount = this.getTodayCount(attendance);
                mHour = mHour + (long) todayCount.get("hour");
                mMin = mMin + (long) todayCount.get("min");
                day = day - 1;// 减去一天
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            List<Attendance> dayCount = baseMapper.selectDayAttendance(attendance);
            // 计算出勤天数
            if (dayCount.size() != 0) {
                days++;
            }
            // 计算正常打卡天数
            if (dayCount.size() != 0 && dayCount.size() % 2 == 0) {
                normal++;
            }

        }
        // 本月总工时
        map.put("mHour", mHour);
        map.put("mMin", mMin);
        // 本月平均工时
        long avg = (mHour * 60 + mMin) / count;
        if (avg < 60) {
            map.put("avgHour", 0);
            map.put("avgMin", avg);
        } else {
            map.put("avgHour", mMin / 60);
            map.put("avgMin", avg % 60);
        }
        // 本月出勤天数
        map.put("days", days);
        /// 本月正常打卡天数
        map.put("normal", normal);

        return map;
    }

    /**
     * 个人： 获取某日总工时
     *
     * @param attendance
     * @return
     */
    public Map<String, Object> getTodayCount(Attendance attendance) {
        long hour = 0;
        long min = 0;
        Date workTime;// 上班时间
        Date releaseTime;// 下班时间
        Long interval;// 间隔时间
        Map<String, Object> map = new HashMap<String, Object>();
        // 找出某一天所有的打卡记录
        List<Attendance> todayList = baseMapper.selectDayAttendance(attendance);

        if (todayList != null && todayList.size() != 1) {
            workTime = new Date();
            releaseTime = new Date();
            interval = 0L;
            // 上下班时间都有的
            if (todayList.size() % 2 == 0) {
                for (int i = todayList.size() - 1; i > 0; i -= 2) {
                    releaseTime = todayList.get(i).getWorkTime();
                    workTime = todayList.get(i - 1).getWorkTime();
                    interval = releaseTime.getTime() - workTime.getTime();
                    interval /= 1000 * 60;
                    hour = hour + interval / 60;
                    min = min + interval % 60;
                }
            } else {// 可能缺少下班时间的情况
                for (int i = todayList.size() - 2; i > 0; i -= 2) {
                    releaseTime = todayList.get(i).getWorkTime();
                    workTime = todayList.get(i - 1).getWorkTime();
                    interval = releaseTime.getTime() - workTime.getTime();
                    interval /= 1000 * 60; // 计算出一共多少分钟
                    hour = hour + interval / 60; // 小时
                    min = min + interval % 60; // 分钟

                }
            }
            if (min >= 60) {
                hour = hour + min / 60;
                min = min % 60;
            }

        }
        map.put("hour", hour);
        map.put("min", min);

        return map;

    }

    /**
     * 个人：获取月打卡记录：用于显示在日历
     *
     * @param month
     * @return
     */
    public Map<String, Object> getMonthRecord(String month, User user) {
        Attendance attendance = new Attendance();
        Map<String, Object> map = new HashMap<String, Object>();
        attendance.setUserid(user.getUserid());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date date;
        Calendar cai = Calendar.getInstance();
        Calendar caj = Calendar.getInstance();
        try {
            date = sdf.parse(month);
            attendance.setWorkTime(date);
            // 这里查出来的记录是一个月中所有的记录。包括一天中的签到记录
            List<Attendance> monthRecord = baseMapper.selectMonthAttendance(attendance);
            for (int i = 0; i < monthRecord.size(); i++) {
                for (int j = monthRecord.size() - 1; j > i; j--) {
                    cai.setTime(monthRecord.get(i).getWorkTime());
                    caj.setTime(monthRecord.get(j).getWorkTime());
                    if (cai.get(Calendar.DAY_OF_MONTH) == caj.get(Calendar.DAY_OF_MONTH)) {
                        // 有一次或一次以上外勤 ，将日历上有外勤记录的标为橘红色
                        if (monthRecord.get(j).getOutState().equals("1")) {
                            monthRecord.get(i).setOutState("1");
                        }
                        monthRecord.remove(j);
                    }
                }
            }

            map.put("monthRecord", monthRecord);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return map;
    }

    /**
     * 团队统计：根据日期获取当天打卡人数，未打卡人数，团队总人数，出勤人数
     *
     * @param date yyyy-MM-dd
     * @return
     * @update 2020/01/03
     * @updateUser LinYuKun
     * @updateContent selectListByDepartId这个内容报错 更换为部门查询 以及大小写
     */
    public Map<String, Object> getTeamRecord(String date, String deptid) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> attUsers = new ArrayList<>();// 出勤员工
        List<Map<String, Object>> outAttUsers = new ArrayList<>();// 外勤员工
        List<Map<String, Object>> notAttUsers = new ArrayList<>();// 未出勤
        // 获取当前用户
        User user = LoginUtils.getCurrentUserInfo();
        if (!StringUtils.isEmpty(deptid)) {
            user.setDeptid(deptid);
        }
        // 查找条件
        Map<String, Object> findmap = new HashMap<String, Object>();
        findmap.put("deptid", user.getDeptid());
        //List<Map<String, Object>> userList = userService.selectList("selectListByDepartId", findmap);

        Dept dept = new Dept();
        dept.setDeptid(user.getDeptid());
        List<Map<String, Object>> userList = new ArrayList();
        if (!StringUtils.isEmpty(dept.getDeptid())) {
            userList = deptService.selectUserByDeptId(dept);
        }
        if (userList != null) {
            // 部门中人数
            map.put("teamNum", userList.size());
        } else {
            map.put("teamNum", 0);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date workDate;
        try {
            workDate = sdf.parse(date);
            findmap.clear();

            for (int i = 0; i < userList.size(); i++) {
                Map<String, Object> tempdata = new HashMap<String, Object>();
                findmap.put("userid", userList.get(i).get("userid"));
                findmap.put("workTime", workDate);
                Integer userOutState = baseMapper.selectOutStateByUserid(findmap);
                tempdata.put("userid", userList.get(i).get("userid"));
                if (userList.get(i).get("headimgurl") != null) {
                    tempdata.put("headimgurl", userList.get(i).get("headimgurl"));
                } else {
                    tempdata.put("headimgurl", userList.get(i).get("theadimgurl"));
                }
                tempdata.put("username", userList.get(i).get("username"));
                tempdata.put("deptname", userList.get(i).get("deptname"));
                if (userOutState == null) {
                    notAttUsers.add(tempdata);
                } else {
                    if (userOutState == 0) {
                        tempdata.put("outState", 0);
                        attUsers.add(tempdata);
                    } else if (userOutState > 0) {
                        tempdata.put("outState", 1);
                        outAttUsers.add(tempdata);
                    }
                }

            }
            attUsers.addAll(outAttUsers);
            // 部门打卡人员
            map.put("attUsers", attUsers);
            // 部门打卡人数
            map.put("teamAtt", attUsers.size());

            // 部门中未打卡人员
            map.put("notAttUsers", notAttUsers);
            // 部门中未打卡人数
            map.put("teamNotAtt", notAttUsers.size());

            // 部门外勤人员
            map.put("outAttUsers", outAttUsers);
            // 部门外勤人数
            map.put("teamOutAtt", outAttUsers.size());
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return map;
    }

    /**
     * 查询某个时刻的打卡信息：用于查询备注
     *
     * @param date
     * @return
     */
    public Attendance getTimeAttendance(String date, User user) {
        Attendance attendance = new Attendance();
        Attendance timeAtt = new Attendance();
        attendance.setUserid(user.getUserid());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            attendance.setWorkTime(sdf.parse(date));
            timeAtt = baseMapper.selectTimeAttendance(attendance);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return timeAtt;
    }

    /**
     * 获取在某个时间段内的考勤记录
     *
     * @param dateBefore
     * @param dateAfter
     * @param attList
     * @return
     */
    public List<Attendance> getAttListOnTime(Date dateBefore, Date dateAfter, List<Attendance> attList) {
        List<Attendance> getAttList = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        for (int i = 0; i < attList.size(); i++) {
            String format = simpleDateFormat.format(attList.get(i).getWorkTime());
            try {
                Date attWorkTime = simpleDateFormat.parse(format);
                if (attWorkTime.after(dateBefore) && attWorkTime.before(dateAfter)) {
                    getAttList.add(attList.get(i));
                }
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return getAttList;
    }


    public void chouli(List<Attendance> workAttList, List<Attendance> reAttList, int foreachNumber, List<Attendance> userAttList) {
        for (int i = 0; i < foreachNumber; i++) {
            if (i % 2 == 0) {
                boolean flag = true;
                for (int j = 0; j < workAttList.size(); j++) {
                    if ((i + "").equals(workAttList.get(j).getBtnPoi())) {
                        userAttList.add(workAttList.get(j));
                        flag = false;
                    }
                }
                if (flag) {
                    Attendance attendanceAdd = new Attendance();
                    attendanceAdd.setState("0");
                    userAttList.add(attendanceAdd);
                }
            } else {
                boolean flag = true;
                for (int j = 0; j < reAttList.size(); j++) {
                    if ((i + "").equals(reAttList.get(j).getBtnPoi())) {
                        userAttList.add(reAttList.get(j));
                        flag = false;
                    }
                }
                if (flag) {
                    Attendance attendanceAdd = new Attendance();
                    attendanceAdd.setState("1");
                    userAttList.add(attendanceAdd);
                }
            }
        }
    }

    public static void main(String[] args) {
        Calendar c = Calendar.getInstance();
        System.out.println(c.get(Calendar.YEAR));
        System.out.println(c.get(Calendar.MONTH));
        System.out.println(c.get(Calendar.DATE));
    }

    /**
     * 获取打卡记录
     *
     * @param date
     * @param deptid
     * @return
     * @Cdate 2020/1/9 14:50
     * @Cauthor LinYuKun
     */
    public Map<String, Object> getTimeAttList(String date, String deptid) {
        Map<String, Object> map = new HashMap<>();
        // 获取当前用户
        User user = LoginUtils.getCurrentUserInfo();
        SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<Attendance> userAttList = new ArrayList<>();
        try {
            Attendance attendance = new Attendance();
            attendance.setUserid(user.getUserid());
            attendance.setWorkTime(yearFormat.parse(date));
            user.setDeptid(deptid);
            // 查询用户所属组别
            Group group = groupService.selectGroupByUseridAndDeptid(user.getUserid(), user.getDeptid());//从登录用户信息里面获取用户所属的部门
            Schedule schedule = new Schedule();
            if (group != null) {
                if (group.getKqType().equals("0")) {

                    // 固定打卡
                    // 根据日期，查询星期几
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(yearFormat.parse(date));
                    int w = cal.get(Calendar.DAY_OF_WEEK) - 1;// 0周日
                    schedule = this.getTodaySchCycleByGroupId(date, group.getId());

                    if (schedule != null) {
                        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
                        // 1.获取用户在指定日期内的所有上班打卡记录
                        List<Attendance> workAttList = baseMapper.selectDayWorkAttendance(attendance);
                        // 2.获取用户在指定日期内的所有下班打卡记录
                        List<Attendance> reAttList = baseMapper.selectDayReleaseAttendance(attendance);

                        Date preDate = null;//上一次的下班时间
                        Date wDate = null;//上班时间
                        Date rDate = null;//下班时间
                        Date nwDate = null;//下次上班时间
                        Integer fixMin = Integer.valueOf(schedule.getFlexibleTime());//弹性时间
                        Integer lateMin = Integer.valueOf(schedule.getLateTime());//下班时间
                        Integer absMin = Integer.valueOf(schedule.getAbsenteeismTime());//旷工时间
                        if (!StringUtils.isEmpty(schedule.getWorkTimec())) {
                            // 一天三次
                            chouli(workAttList, reAttList, 6, userAttList);
                            map.putAll(judgeBtn(userAttList, schedule, 3));

							/*wDate = format.parse(schedule.getWorkTimea());//a段上班时间
							rDate = format.parse(schedule.getReleaseTimea());//a段下班时间
							nwDate = format.parse(schedule.getWorkTimea());//取错了
							userAttList = getOnceAttList(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin,
									workAttList, reAttList);

							preDate = format.parse(schedule.getReleaseTimea());
							wDate = format.parse(schedule.getWorkTimeb());
							rDate = format.parse(schedule.getReleaseTimeb());
							nwDate = format.parse(schedule.getWorkTimec());
							userAttList.addAll(getOnceAttList(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin,
									workAttList, reAttList));

							preDate = format.parse(schedule.getReleaseTimeb());
							wDate = format.parse(schedule.getWorkTimec());
							rDate = format.parse(schedule.getReleaseTimec());
							nwDate = null;
							userAttList.addAll(getOnceAttList(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin,
									workAttList, reAttList));
							map.put("userAttList", userAttList);
							map.putAll(judgeBtn(userAttList, schedule, 3));*/

                        } else if (!StringUtils.isEmpty(schedule.getWorkTimeb())) {
                            // 一天两次
                            chouli(workAttList, reAttList, 4, userAttList);
                            map.putAll(judgeBtn(userAttList, schedule, 2));


							/*userAttList.set(1, reAttList.get(0));
							userAttList.set(2, workAttList.get(0));*/
							/*wDate = format.parse(schedule.getWorkTimea());
							rDate = format.parse(schedule.getReleaseTimea());
							nwDate = format.parse(schedule.getWorkTimeb());
							userAttList = getOnceAttList(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin,
									workAttList, reAttList);

							preDate = format.parse(schedule.getReleaseTimea());
							wDate = format.parse(schedule.getWorkTimeb());
							rDate = format.parse(schedule.getReleaseTimeb());
							nwDate = null;
							userAttList.addAll(getOnceAttList(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin,
									workAttList, reAttList));
							map.put("userAttList", userAttList);*/
                            //map.putAll(judgeBtn(userAttList, schedule, 2));
                        } else if (!StringUtils.isEmpty(schedule.getWorkTimea())) {
                            // 一天一次
							/*wDate = format.parse(schedule.getWorkTimea());
							rDate = format.parse(schedule.getReleaseTimea());*/
                            //第一个参数是空  第二个参数 上班时间 第三个参数是下班时间
						/*userAttList = getOnceAttList(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin,
									workAttList, reAttList);
							map.putAll(judgeBtn(userAttList, schedule, 1));*/
                            chouli(workAttList, reAttList, 2, userAttList);
                            map.putAll(judgeBtn(userAttList, schedule, 1));
                        }
                    } else {
                        // 当天休息
                        userAttList = baseMapper.selectDayAttendance(attendance);
                    }

                } else if (group.getKqType().equals("2")) {
                    // 自由打卡
                    userAttList = baseMapper.selectDayAttendance(attendance);
                }
            } else {
                // 没有组别，自由打卡
                userAttList = baseMapper.selectDayAttendance(attendance);//根据用户和时间
            }
            map.put("userAttList", userAttList);
            map.put("group", group);
            map.put("schedule", schedule);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return map;
    }

    /**
     * 获取一次上下班的打卡记录
     *
     * @param preDate              :上一次的下班时间
     * @param wDate:上班时间
     * @param rDate：下班时间
     * @param nwDate：下次的上班时间
     * @param fixMin：弹性时间
     * @param lateMin：严重迟到时间
     * @param absMin：旷工时间
     * @param workAttList：实际上班打卡列表
     * @param reAttList：实际下班打卡列表
     * @return
     * @cContent 删除了部门代码
     * @cdate 2020/1/9 14:01
     * @author LinYuKun
     */
    public List<Attendance> getOnceAttList(Date preDate, Date wDate, Date rDate, Date nwDate, Integer fixMin, Integer lateMin, Integer absMin, List<Attendance> workAttList, List<Attendance> reAttList) {
        List<Attendance> userAttList = new ArrayList<>();//返回的结果 如果没有下班记录就是下班缺卡 如果没有上班记录就是上班旷工
        try {
            if (workAttList != null && workAttList.size() > 0) {//如果没有上班打卡记录 就变为上班旷工
                //userAttList.addAll(workAttList);
                Attendance normalWorkAtt = getNormalWorkAtt(preDate, wDate, fixMin, workAttList);
                if (normalWorkAtt != null) {
                    userAttList.add(normalWorkAtt);
                } else {
                    // 迟到
                    Attendance lateWorkAtt = getLateWorkAtt(wDate, fixMin, lateMin, workAttList);
                    if (lateWorkAtt != null) {
                        userAttList.add(lateWorkAtt);
                    } else {
                        // 严重迟到
                        Attendance seriesLateWorkAtt = getSeriesLateWorkAtt(wDate, fixMin, lateMin, absMin, workAttList);
                        if (seriesLateWorkAtt != null) {
                            userAttList.add(seriesLateWorkAtt);
                        } else {
                            // 旷工
                            Attendance absWorkAtt = getAbsWorkAtt(wDate, rDate, fixMin, lateMin, absMin, workAttList);
                            userAttList.add(absWorkAtt);
                        }
                    }

                }
            } else {
                // 旷工
                Attendance absWorkAtt = new Attendance();
                absWorkAtt.setOntimeState("3");
                absWorkAtt.setState("0");
                userAttList.add(absWorkAtt);
            }

            if (reAttList != null && reAttList.size() > 0) {//如果没有下班记录
                userAttList.addAll(reAttList);
                // 下班
				/*Attendance earlyReAtt = getEarlyReAtt(userAttList.get(0), wDate, rDate, fixMin, reAttList);
				if (earlyReAtt != null) {
					// 早退
					userAttList.add(earlyReAtt);
				} else {
					// 正常
					Attendance normalReAtt = getNormalReAtt(userAttList.get(0), wDate, rDate, fixMin, nwDate,
							reAttList);
					if (normalReAtt != null) {
						userAttList.add(normalReAtt);
					} else {
						normalReAtt = new Attendance();
						normalReAtt.setState("1");
						normalReAtt.setOntimeState("5");// 缺卡
						userAttList.add(normalReAtt);
					}
				}*/

            } else {
                Attendance normalReAtt = new Attendance();
                normalReAtt.setState("1");
                normalReAtt.setOntimeState("5");// 缺卡
                userAttList.add(normalReAtt);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

        return userAttList;
    }

    /**
     * 获取正常上班 PreReDate:前一个上班时间 wDate:上班时间 fixMin:弹性上班时间
     *
     * @return
     * @throws ParseException
     */
    public Attendance getNormalWorkAtt(Date PreReDate, Date wDate, Integer fixMin, List<Attendance> workAttList) throws ParseException {
        // PreReDate 到 wDate+fixMin
        Attendance attendance = null;
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        if (PreReDate == null) {
            PreReDate = format.parse("00:00");
        }
        long timeH = ((wDate.getTime() / 1000L) + fixMin * 60L) * 1000L;
        Date workDate = new Date();
        workDate.setTime(timeH);
        List<Attendance> normalList = getAttListOnTime(PreReDate, workDate, workAttList);
        if (normalList != null && normalList.size() > 0) {
            normalList.get(0).setOntimeState("0");// 正常
            attendance = normalList.get(0);
        }
        return attendance;
    }

    /**
     * 打卡时，判断当前是否属于正常状态
     * 注意dkDate:打卡日期必须 HH:mm形式
     *
     * @return
     * @throws ParseException
     */
    public int getNormalOntimeState(Date preReDate, Date wDate, Date dkDate, Integer fixMin) throws ParseException {
        // PreReDate 到 wDate+fixMin
        int state = 0;
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        if (preReDate == null) {
            preReDate = format.parse("00:00");
        }
        long timeH = ((wDate.getTime() / 1000) + fixMin * 60) * 1000;
        Date finallyWDate = new Date();
        finallyWDate.setTime(timeH);
        if (dkDate.before(finallyWDate) && dkDate.after(preReDate)) {
            state = 0;
        } else {
            state = -1;
        }
        return state;
    }

    /**
     * 获取迟到记录 上班 wDate 弹性fixDate 严重seriesMin
     *
     * @return
     * @throws ParseException
     */
    public Attendance getLateWorkAtt(Date wDate, Integer fixMin, Integer seriesMin, List<Attendance> workAttList) throws ParseException {
        // wDate+fixMin 到 wDate+fixMin+seriesMin
        Attendance attendance = null;
        // wDate+fixMin
        long timef = ((wDate.getTime() / 1000) + fixMin * 60) * 1000;
        Date wFixDate = new Date();
        wFixDate.setTime(timef);
        // wDate+fixMin+seriesMin
        timef = ((wDate.getTime() / 1000) + (fixMin + seriesMin) * 60) * 1000;
        Date wFixSerDate = new Date();
        wFixSerDate.setTime(timef);

        List<Attendance> lateList = getAttListOnTime(wFixDate, wFixSerDate, workAttList);
        if (lateList != null && lateList.size() > 0) {
            lateList.get(0).setOntimeState("1");// 迟到
            attendance = lateList.get(0);
        }
        return attendance;
    }

    /**
     * 打卡时，判断当前是否属于迟到状态
     * 注意dkDate:打卡日期必须 HH:mm形式
     *
     * @return
     * @throws ParseException
     */
    public int getLateOntimeState(Date wDate, Integer fixMin, Integer seriesMin, Date dkDate) throws ParseException {
        // wDate+fixMin 到 wDate+fixMin+seriesMin
        int state = 1;
        // wDate+fixMin
        long timef = ((wDate.getTime() / 1000) + fixMin * 60) * 1000;
        Date wFixDate = new Date();
        wFixDate.setTime(timef);
        // wDate+fixMin+seriesMin
        timef = ((wDate.getTime() / 1000) + (fixMin + seriesMin) * 60) * 1000;
        Date wFixSerDate = new Date();
        wFixSerDate.setTime(timef);
        if (dkDate.after(wFixDate) && dkDate.before(wFixSerDate)) {
            state = 1;
        } else {
            state = -1;
        }
        return state;
    }

    /**
     * 打卡时，判断当前是否属于严重迟到状态
     * 注意dkDate:打卡日期必须 HH:mm形式
     *
     * @return
     * @throws ParseException
     */
    public int getSeriesLateOntimeState(Date wDate, Integer fixMin, Integer seriesMin, Integer absMin, Date dkDate) throws ParseException {
        // wDate+fixMin+seriesMin 到 wDate+fixMin+seriesMin+absMin
        int state = 2;
        // wDate+fixMin+seriesMin
        long timef = ((wDate.getTime() / 1000) + (fixMin + seriesMin) * 60) * 1000;
        Date wFixSerDate = new Date();
        wFixSerDate.setTime(timef);
        // wDate+fixMin+seriesMin+absMin
        timef = ((wDate.getTime() / 1000) + (fixMin + seriesMin + absMin) * 60) * 1000;
        Date wFixSerAbsDate = new Date();
        wFixSerAbsDate.setTime(timef);
        if (dkDate.before(wFixSerAbsDate) && dkDate.after(wFixSerDate)) {
            state = 2;
        } else {
            state = -1;
        }
        return state;
    }

    /**
     * 获取严重迟到记录 上班 wDate 弹性fixDate 严重seriesMin 旷工时间 absMin
     *
     * @return
     * @throws ParseException
     */
    public Attendance getSeriesLateWorkAtt(Date wDate, Integer fixMin, Integer seriesMin, Integer absMin, List<Attendance> workAttList) throws ParseException {
        // wDate+fixMin+seriesMin 到 wDate+fixMin+seriesMin+absMin
        Attendance attendance = null;
        // wDate+fixMin+seriesMin
        long timef = ((wDate.getTime() / 1000) + (fixMin + seriesMin) * 60) * 1000;
        Date wFixSerDate = new Date();
        wFixSerDate.setTime(timef);
        // wDate+fixMin+seriesMin+absMin
        timef = ((wDate.getTime() / 1000) + (fixMin + seriesMin + absMin) * 60) * 1000;
        Date wFixSerAbsDate = new Date();
        wFixSerAbsDate.setTime(timef);
        List<Attendance> serLateList = getAttListOnTime(wFixSerDate, wFixSerAbsDate, workAttList);
        if (serLateList != null && serLateList.size() > 0) {
            serLateList.get(0).setOntimeState("2");// 严重迟到
            attendance = serLateList.get(0);
        }
        return attendance;
    }


    /**
     * 获取旷工记录 上班 wDate 弹性fixDate 严重seriesMin 旷工时间 absMin 下班rDate
     *
     * @return
     * @throws ParseException
     */
    public Attendance getAbsWorkAtt(Date wDate, Date rDate, Integer fixMin, Integer seriesMin, Integer absMin, List<Attendance> workAttList) throws ParseException {
        // wDate+fixMin+seriesMin+absMin 到 rDate
        Attendance attendance = new Attendance();
        // wDate+fixMin+seriesMin+absMin
        long timef = ((wDate.getTime() / 1000) + (fixMin + seriesMin + absMin) * 60) * 1000;
        Date wFixSerAbsDate = new Date();
        wFixSerAbsDate.setTime(timef);

        List<Attendance> serLateList = getAttListOnTime(wFixSerAbsDate, rDate, workAttList);
        if (serLateList != null && serLateList.size() > 0) {
            serLateList.get(0).setOntimeState("3");// 旷工
            attendance = serLateList.get(0);
        } else {
            attendance.setOntimeState("3");
        }
        attendance.setState("0");
        return attendance;
    }

    /**
     * 打卡时，判断当前是否属于旷工状态
     * 注意dkDate:打卡日期必须 HH:mm形式
     *
     * @return
     * @throws ParseException
     */
    public int getAbsOntimestate(Date wDate, Date rDate, Integer fixMin, Integer seriesMin, Integer absMin, Date dkDate) throws ParseException {
        // wDate+fixMin+seriesMin+absMin 到 rDate
        int state = 3;
        // wDate+fixMin+seriesMin+absMin
        long timef = ((wDate.getTime() / 1000) + (fixMin + seriesMin + absMin) * 60) * 1000;
        Date wFixSerAbsDate = new Date();
        wFixSerAbsDate.setTime(timef);
        //if (dkDate.before(rDate)&&dkDate.after(wFixSerAbsDate)) {
        if (dkDate.after(wFixSerAbsDate)) {
            state = 3;
        } else {
            state = -1;
        }
        return state;
    }

    /**
     * 获取下班早退记录 实际上班记录trueAtt ,实际上班时间trueDate 上班时间wDate 下班时间rDate
     * 实际弹性时间trueFixTime
     *
     * @return
     * @throws ParseException
     */
    public Attendance getEarlyReAtt(Attendance trueAtt, Date wDate, Date rDate, long fixMin, List<Attendance> reList) throws ParseException {
        // 1.trueAtt！=null, trueDate 到 (rDate+trueFixTime)
        // 2.trueAtt==null, wDate 到 rDate
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        Attendance attendance = null;
        if (trueAtt != null) {
            // trueDate
            Date trueDate = format.parse(format.format(trueAtt.getWorkTime()));
            // 获取实际弹性时间
            long trueFixTime = truelyFixTime(trueAtt.getWorkTime(), fixMin, wDate);
            // rDate+trueFixTime
            long timef = ((rDate.getTime() / 1000) + trueFixTime * 60) * 1000;
            rDate.setTime(timef);

            List<Attendance> earlyReList = getAttListOnTime(trueDate, rDate, reList);
            if (earlyReList != null && earlyReList.size() > 0) {
                earlyReList.get(earlyReList.size() - 1).setOntimeState("4");// 早退
                attendance = earlyReList.get(earlyReList.size() - 1);
            }
        } else {
            List<Attendance> earlyReList = getAttListOnTime(wDate, rDate, reList);
            if (earlyReList != null && earlyReList.size() > 0) {
                earlyReList.get(earlyReList.size() - 1).setOntimeState("4");// 早退
                attendance = earlyReList.get(earlyReList.size() - 1);
            }
        }
        return attendance;
    }

    /**
     * 打卡时，判断当前是否属于早退状态
     * 注意dkDate:打卡日期必须 HH:mm形式
     * trueAtt:上次上班打卡
     *
     * @return
     * @throws ParseException
     * @cauthor LinYuKun
     */
    public int getEarlyOntimeState(Attendance trueAtt, Date wDate, Date rDate, long fixMin, Date dkDate) throws ParseException {//		上班对象 			上班时间   		下班时间 		 弹性时间  		打卡时间
        // 1.trueAtt！=null, trueDate 到 (rDate+trueFixTime)
        // 2.trueAtt==null, wDate 到 rDate
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        int state = 4;
        if (trueAtt != null) {
            // trueDate
            Date trueDate = format.parse(format.format(trueAtt.getWorkTime()));
            // 获取实际弹性时间
            long trueFixTime = truelyFixTime(trueAtt.getWorkTime(), fixMin, wDate);
            // rDate+trueFixTime
            long timef = ((rDate.getTime() / 1000) + trueFixTime * 60) * 1000;
            //rDate.setTime(timef);

            //if (dkDate.before(rDate)&&dkDate.after(trueDate)) {
            if (dkDate.before(rDate)) {//如果打卡时间在下班之前
                state = 4;//表示早退
            } else {
                //state=-1;
                state = 0;
            }
        } else {
            if (dkDate.before(rDate) && dkDate.after(wDate)) {
                state = 4;
            } else {
                state = -1;
            }
        }
        return state;
    }

    /**
     * 实际弹性时间
     *
     * @return
     * @throws ParseException
     */
    public long truelyFixTime(Date attDate, long fixMin, Date wDate) throws ParseException {

        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        long truelyFixTime = 0;
        if (attDate != null) {
            attDate = format.parse(format.format(attDate));
            truelyFixTime = attDate.getTime() - wDate.getTime();
            truelyFixTime = truelyFixTime / 1000 / 60;// 分钟
            if (truelyFixTime > fixMin) {
                truelyFixTime = fixMin;
            }
        }
        return truelyFixTime;
    }

    /**
     * 获取正常打卡记录
     *
     * @param trueAtt :实际上次打卡上班记录
     * @param rDate   :下班时间
     * @param wDate   :上班时间
     * @param fixMin  :弹性时间
     * @param nwDate  :下次上班时间
     * @param reList  :下班记录列表
     * @return
     * @throws ParseException
     */
    public Attendance getNormalReAtt(Attendance trueAtt, Date wDate, Date rDate, long fixMin, Date nwDate, List<Attendance> reList) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        // (rDate+实际弹性) 到 nwDate
        Attendance attendance = null;
        if (trueAtt != null) {
            // 获取实际弹性时间
            long trueFixTime = truelyFixTime(trueAtt.getWorkTime(), fixMin, wDate);
            // rDate+trueFixTime
            long timef = ((rDate.getTime() / 1000) + trueFixTime * 60) * 1000;
            rDate.setTime(timef);
            if (nwDate == null) {
                nwDate = simpleDateFormat.parse("23:59");
            }
            List<Attendance> normalReList = getAttListOnTime(rDate, nwDate, reList);
            if (normalReList != null && normalReList.size() > 0) {
                normalReList.get(normalReList.size() - 1).setOntimeState("0");// 正常下班
                attendance = normalReList.get(normalReList.size() - 1);
            }
        } else {
            List<Attendance> normalReList = getAttListOnTime(rDate, nwDate, reList);
            if (normalReList != null && normalReList.size() > 0) {
                normalReList.get(normalReList.size() - 1).setOntimeState("0");// 正常下班
                attendance = normalReList.get(normalReList.size() - 1);
            }
        }
        return attendance;
    }

    /**
     * 打卡时，判断当前是否属于下班正常状态
     * 注意dkDate:打卡日期必须 HH:mm形式
     *
     * @param trueAtt
     * @param wDate
     * @param rDate
     * @param fixMin
     * @param nwDate
     * @return
     * @throws ParseException
     */
    public int getNormalReOntimeState(Attendance trueAtt, Date wDate, Date rDate, long fixMin, Date nwDate, Date dkDate) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        // (rDate+实际弹性) 到 nwDate
        int state = 0;
        if (trueAtt != null) {
            // 获取实际弹性时间
            long trueFixTime = truelyFixTime(trueAtt.getWorkTime(), fixMin, wDate);
            // rDate+trueFixTime
            long timef = ((rDate.getTime() / 1000) + trueFixTime * 60) * 1000;
            rDate.setTime(timef);
            if (nwDate == null) {
                nwDate = simpleDateFormat.parse("23:59");
            }
            if (dkDate.before(nwDate) && dkDate.after(rDate)) {
                state = 0;
            } else {
                state = -1;
            }
        } else {
            if (dkDate.before(nwDate) && dkDate.after(rDate)) {
                state = 0;
            } else {
                state = -1;
            }
        }
        return state;
    }


    /**
     * 判断按钮位置
     * status:当前是一天一次、还是一天两次。还是一天三次
     *
     * @return
     * @throws ParseException
     */
    public Map<String, Object> judgeBtn(List<Attendance> attList, Schedule schedule, int status) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        Map<String, Object> map = new HashMap<>();
        //int btnPoi=0;
        int btnPoi = -1;//0表示第一个位置 1表示第二个位置 2表示第三个位置 3表示第四个位置 4表示第五个位置 5表示第六个位置
        int btnState = 0;//0表示上班1表示下班
        //当前时间
        Date date = format.parse(format.format(new Date()));
        if (status == 1) {//如果是一天打一次卡
            //当前时间<a段下班时间时
            if (!date.after(format.parse(schedule.getReleaseTimea()))) {//如果当前时间是在a段下班时间之前
                if (attList.get(0).getWorkTime() != null && attList.get(1).getWorkTime() == null) {//如果第一次打卡不为空并且第二次打卡为空   则表示现在应该是打下班卡
                    btnPoi = 1;//第二个位置  这个貌似看成了一个数组
                    btnState = 1;//下班
                } else if (attList.get(0).getWorkTime() == null) {//如果第一次打卡为空  则表示打上班卡
                    btnPoi = 0;//第一个位置 表示打卡按钮的位置 0表示第一个并且该按钮的ontimeState不需要显示
                    btnState = 0;//上班
                } else if (attList.get(0).getWorkTime() == null) {//无用代码
                    btnPoi = -1;
                }
            }
            //当前时间>=下班时间时
            if (date.after(format.parse(schedule.getReleaseTimea()))) {//如果当前时间大于下班时间
                if (attList.get(1).getWorkTime() == null) {//如果第二次打卡记录为空 则表示打下班卡
                    btnPoi = 1;//第二个位置
                    btnState = 1;//下班
                }/*else if (attList.get(1).getWorkTime()!=null) {//如果已经打过卡了
					btnPoi=-1;//就不能打卡了
				}*/
            }
            if (attList.get(1).getWorkTime() != null) {//如果已经打过卡了   如果第二次表示的下班时间不为空 则表示打过了
                btnPoi = -1;//就不能打卡了
            }
        } else if (status == 2) {//一天两次的
            //当前时间<第一次下班时间时
            if (!date.after(format.parse(schedule.getReleaseTimea()))) {
                if (attList.get(0).getWorkTime() != null && attList.get(1).getWorkTime() == null) {
                    btnPoi = 1;
                    btnState = 1;
                } else if (attList.get(0).getWorkTime() == null) {
                    btnPoi = 0;
                    btnState = 0;
                } else if (attList.get(0).getWorkTime() == null) {//无用代码
                    btnPoi = 2;
                    btnState = 0;
                }
            }
            //当前时间>=第一次下班时间时  并且 <第二次上班时间时
            if (date.after(format.parse(schedule.getReleaseTimea())) && !date.after(format.parse(schedule.getWorkTimeb()))) {
                if (attList.get(1).getWorkTime() == null) {
                    btnPoi = 1;
                    btnState = 1;
                } else if (attList.get(1).getWorkTime() != null) {
                    btnPoi = 2;
                    btnState = 0;
                }
            }
            //当前时间>=第一次下班时间 并且<第二次下班时间时
            if (date.after(format.parse(schedule.getReleaseTimea())) && !date.after(format.parse(schedule.getReleaseTimeb()))) {
                if (attList.get(2).getWorkTime() != null && attList.get(3).getWorkTime() == null) {
                    btnPoi = 3;
                    btnState = 1;
                } else if (attList.get(2).getWorkTime() == null) {
                    btnPoi = 2;
                    btnState = 0;
                } else if (attList.get(2).getWorkTime() != null && attList.get(3).getWorkTime() != null) {
                    btnPoi = -1;
                }
            }
            //当前时间>=第二次上班时间时
            if (date.after(format.parse(schedule.getReleaseTimeb()))) {
                if (attList.get(3).getWorkTime() == null) {
                    btnPoi = 3;
                    btnState = 1;
                } else if (attList.get(3).getWorkTime() != null) {
                    btnPoi = -1;
                }
            }
        } else if (status == 3) {//一天三次的
            //当前时间<第一次下班时间时
            if (!date.after(format.parse(schedule.getReleaseTimea()))) {
                if (attList.get(0).getWorkTime() != null && attList.get(1).getWorkTime() == null) {
                    btnPoi = 1;
                    btnState = 1;
                } else if (attList.get(0).getWorkTime() == null) {
                    btnPoi = 0;
                    btnState = 0;
                } else if (attList.get(0).getWorkTime() == null) {
                    btnPoi = 2;
                    btnState = 0;
                }
            }
            //当前时间>=第一次下班时间时  并且 <第二次上班时间时
            if (date.after(format.parse(schedule.getReleaseTimea())) && !date.after(format.parse(schedule.getWorkTimeb()))) {
                if (attList.get(1).getWorkTime() == null) {
                    btnPoi = 1;
                    btnState = 1;
                    map.put("btnPoi", btnPoi);
                    map.put("btnState", btnState);
                    return map;
                } else if (attList.get(1).getWorkTime() != null) {
                    btnPoi = 2;
                    btnState = 0;
					/*map.put("btnPoi",btnPoi );
					map.put("btnState",btnState );
					return map;*/
                }
            }
            //当前时间>=第一次下班时间 并且<第二次下班时间时
            if (date.after(format.parse(schedule.getReleaseTimea())) && !date.after(format.parse(schedule.getReleaseTimeb()))) {
                if (attList.get(2).getWorkTime() != null && attList.get(3).getWorkTime() == null) {
                    btnPoi = 3;
                    btnState = 1;
                } else if (attList.get(2).getWorkTime() == null) {
                    btnPoi = 2;
                    btnState = 0;
                } else if (attList.get(2).getWorkTime() != null && attList.get(3).getWorkTime() != null) {
                    btnPoi = 4;
                    btnState = 0;
                }
            }

            //当前时间>=第二次下班时间 并且<第三次上班时间时
            if (date.after(format.parse(schedule.getReleaseTimeb())) && !date.after(format.parse(schedule.getWorkTimec()))) {
                if (attList.get(3).getWorkTime() == null) {
                    btnPoi = 3;
                    btnState = 1;
                    map.put("btnPoi", btnPoi);
                    map.put("btnState", btnState);
                    return map;
                } else if (attList.get(3).getWorkTime() != null) {
                    btnPoi = 4;
                    btnState = 0;
                }
            }
            //当前时间>=第二次下班时间 并且<第三次下班时间时
            if (date.after(format.parse(schedule.getReleaseTimeb())) && !date.after(format.parse(schedule.getReleaseTimec()))) {
                if (attList.get(4).getWorkTime() != null && attList.get(5).getWorkTime() == null) {
                    btnPoi = 5;
                    btnState = 1;
                } else if (attList.get(4).getWorkTime() == null) {
                    btnPoi = 4;
                    btnState = 0;
                } else if (attList.get(4).getWorkTime() != null && attList.get(5).getWorkTime() != null) {
                    btnPoi = -1;
                }
            }
            //当前时间>=第三次上班时间时
            if (date.after(format.parse(schedule.getReleaseTimec()))) {
                if (attList.get(5).getWorkTime() == null) {
                    btnPoi = 4;
                    btnState = 1;
                } else if (attList.get(5).getWorkTime() != null) {
                    btnPoi = -1;
                }
            }
        }
        map.put("btnPoi", btnPoi);
        map.put("btnState", btnState);
        return map;
    }


    /**
     * 判断用户当前打卡记录属于什么状态
     * 0正常1迟到2严重迟到3旷工4早退5缺卡
     * btnPoi:打卡时，按钮的位置
     *
     * @param user
     * @return
     */
    public int getOntimeState(User user, Attendance attendance, String btnPoi, String deptid) {
        SimpleDateFormat yearFormat = new SimpleDateFormat("HH:mm");
        int onTimeState = 0;
        try {

            // 查询用户所属组别
            Group group = groupService.selectGroupByUseridAndDeptid(user.getUserid(), user.getDeptid());

            // 固定打卡
            // 根据日期，查询星期几
			/*Calendar cal = Calendar.getInstance();
			cal.setTime(new Date());
			int w = cal.get(Calendar.DAY_OF_WEEK) - 1;// 0周日
			GroupScheduleCycle groupSchCycle = groupScheduleCycleService.selectOne("selectSchCycleByGroupId",
					group.getId());
			Schedule schedule=new Schedule();
			if (w == 0) {// 周日
				schedule.setId(groupSchCycle.getSunday());
			} else if (w == 1) {// 周一
				schedule.setId(groupSchCycle.getMonday());
			} else if (w == 2) {// 周二
				schedule.setId(groupSchCycle.getTuesday());
			} else if (w == 3) {// 周三
				schedule.setId(groupSchCycle.getWednesday());
			} else if (w == 4) {// 周四
				schedule.setId(groupSchCycle.getThursday());
			} else if (w == 5) {// 周五
				schedule.setId(groupSchCycle.getFriday());
			} else if (w == 6) {// 周六
				schedule.setId(groupSchCycle.getSaturday());
			}*/


            if (group != null) {
                if (group.getKqType().equals("2")) {//自由
                    onTimeState = 0;
                } else if (group.getKqType().equals("0")) {//固定
                    // 当天的考勤规则
                    Schedule schedule = new Schedule();
                    schedule = this.getTodaySchCycleByGroupId(null, group.getId());

                    //schedule = scheduleService.selectOneObject(schedule);
                    if (schedule != null) {//如果没有考勤规则就是休息
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
                        SimpleDateFormat formatb = new SimpleDateFormat("HH:mm");
                        Map<String, Object> timeAttList = getTimeAttList(simpleDateFormat.format(new Date()), deptid);
                        List<Attendance> userAttList = (List<Attendance>) timeAttList.get("userAttList");
                        Date preDate = null;//前一个下班时间
                        Date wDate = null;
                        Date rDate = null;
                        Date nwDate = null;//下一个上班时间
                        Date dkDate = attendance.getWorkTime();
                        String wstate = attendance.getState();//上下班状态
                        Integer fixMin = Integer.valueOf(schedule.getFlexibleTime());
                        Integer lateMin = Integer.valueOf(schedule.getLateTime());
                        Integer absMin = Integer.valueOf(schedule.getAbsenteeismTime());

                        if (!StringUtils.isEmpty(schedule.getWorkTimec())) {
                            if (btnPoi.equals("0") || btnPoi.equals("1")) {
                                //当前时间在第一个时间段
                                wDate = formatb.parse(schedule.getWorkTimea());
                                rDate = formatb.parse(schedule.getReleaseTimea());
                                nwDate = formatb.parse(schedule.getWorkTimeb());
                                dkDate = formatb.parse(format.format(dkDate));
                                if (userAttList.get(0).getWorkTime() != null || btnPoi.equals("1")) {
                                    onTimeState = getOnceAttOnTimeState(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin, dkDate, userAttList.get(0), wstate);
                                } else {
                                    onTimeState = getOnceAttOnTimeState(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin, dkDate, null, wstate);
                                }
                            } else if (btnPoi.equals("2") || btnPoi.equals("3")) {
                                //当前时间在第二个时间段
                                preDate = formatb.parse(schedule.getReleaseTimea());
                                wDate = formatb.parse(schedule.getWorkTimeb());
                                rDate = formatb.parse(schedule.getReleaseTimeb());
                                nwDate = formatb.parse(schedule.getWorkTimec());
                                dkDate = formatb.parse(format.format(dkDate));
                                if (userAttList.get(2).getWorkTime() != null || btnPoi.equals("3")) {
                                    onTimeState = getOnceAttOnTimeState(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin, dkDate, userAttList.get(2), wstate);
                                } else {
                                    onTimeState = getOnceAttOnTimeState(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin, dkDate, null, wstate);
                                }

                            } else if (btnPoi.equals("4") || btnPoi.equals("5")) {
                                //当前时间在第三个时间段
                                //当前时间在第三个时间段
                                preDate = formatb.parse(schedule.getReleaseTimeb());
                                wDate = formatb.parse(schedule.getWorkTimec());
                                rDate = formatb.parse(schedule.getReleaseTimec());
                                dkDate = formatb.parse(format.format(dkDate));

                                if (userAttList.get(4).getWorkTime() != null || btnPoi.equals("5")) {
                                    onTimeState = getOnceAttOnTimeState(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin, dkDate, userAttList.get(4), wstate);
                                } else {
                                    onTimeState = getOnceAttOnTimeState(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin, dkDate, null, wstate);
                                }

                            }

                        } else if (!StringUtils.isEmpty(schedule.getWorkTimeb())) {
                            if (btnPoi.equals("0") || btnPoi.equals("1")) {
                                //在第一个时间段
                                wDate = formatb.parse(schedule.getWorkTimea());
                                rDate = formatb.parse(schedule.getReleaseTimea());
                                nwDate = formatb.parse(schedule.getWorkTimeb());
                                dkDate = formatb.parse(format.format(dkDate));

                                //onTimeState=getOnceAttOnTimeState(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin, dkDate, userAttList.get(0),wstate);
                                if (userAttList.get(0).getWorkTime() != null && btnPoi.equals("1")) {
                                    onTimeState = getOnceAttOnTimeState(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin, dkDate, userAttList.get(0), wstate);
                                } else {
                                    onTimeState = getOnceAttOnTimeState(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin, dkDate, null, wstate);
                                }
                            } else if (btnPoi.equals("2") || btnPoi.equals("3")) {
                                //在第二个时间段
                                preDate = formatb.parse(schedule.getReleaseTimea());
                                wDate = formatb.parse(schedule.getWorkTimeb());
                                rDate = formatb.parse(schedule.getReleaseTimeb());
                                dkDate = formatb.parse(format.format(dkDate));
                                if (userAttList.get(2).getWorkTime() != null && btnPoi.equals("3")) {
                                    onTimeState = getOnceAttOnTimeState(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin, dkDate, userAttList.get(2), wstate);
                                } else {
                                    onTimeState = getOnceAttOnTimeState(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin, dkDate, null, wstate);
                                }

                            }
                        } else if (!StringUtils.isEmpty(schedule.getWorkTimea())) {
                            if (btnPoi.equals("0") || btnPoi.equals("1")) {
                                dkDate = formatb.parse(format.format(dkDate));
                                wDate = formatb.parse(schedule.getWorkTimea());
                                rDate = formatb.parse(schedule.getReleaseTimea());
                                if (!StringUtils.isEmpty(userAttList.get(0).getWorkTime()) && btnPoi.equals("1")) {
                                    onTimeState = getOnceAttOnTimeState(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin, dkDate, userAttList.get(0), wstate);
                                } else {
                                    onTimeState = getOnceAttOnTimeState(preDate, wDate, rDate, nwDate, fixMin, lateMin, absMin, dkDate, null, wstate);
                                }
                            }

                        }
                    } else {//当天休息
                        onTimeState = 0;
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return onTimeState;
    }

    /**
     * 判断某个指定时间段内某条记录的状态
     *
     * @param preDate
     * @param wDate
     * @param rDate
     * @param nwDate
     * @param fixMin
     * @param lateMin
     * @param absMin
     * @param dkDate
     * @param trueAtt：实际上班打卡记录
     * @param wstate:上下班状态
     * @return
     * @CAuthor LinYuKun
     * @Cdate 2020/1/9 14:39
     */
    public int getOnceAttOnTimeState(Date preDate, Date wDate, Date rDate, Date nwDate, Integer fixMin, Integer lateMin, Integer absMin, Date dkDate, Attendance trueAtt, String wstate) {

        int state = 0;
        try {
            SimpleDateFormat format = new SimpleDateFormat("HH:mm");
            dkDate = format.parse(format.format(dkDate));
            if (wstate.equals(0) || "0".equals(wstate)) {//上班
                // 正常
                state = getNormalOntimeState(preDate, wDate, dkDate, fixMin);
                if (state < 0) {
                    //迟到
                    //state=getLateOntimeState(nwDate, fixMin, lateMin, dkDate);
                    state = getLateOntimeState(wDate, fixMin, lateMin, dkDate);
                    if (state < 0) {
                        //严重迟到
                        state = getSeriesLateOntimeState(wDate, fixMin, lateMin, absMin, dkDate);
                        if (state < 0) {
                            //旷工
                            state = getAbsOntimestate(wDate, rDate, fixMin, lateMin, absMin, dkDate);
                        }
                    }
                }
            } else {//下班判断
                //早退  判断打卡时间是不是在下班时间之前
                state = getEarlyOntimeState(trueAtt, wDate, rDate, fixMin, dkDate);//上班对象，上班时间， 下班时间
                if (state < 0) {
                    //正常下班
                    state = getEarlyOntimeState(trueAtt, wDate, rDate, fixMin, dkDate);//和上面的方法一样
                    if (state < 0) {
                        //state=5;//缺卡
                        state = 0;
                    }
                }
            }


        } catch (Exception e) {
            // TODO: handle exception
        }

        return state;
    }


    //通过组id获取今天的考勤规则
    public Schedule getTodaySchCycleByGroupId(String date, String groupId) throws Exception {
        SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        if (StringUtils.isEmpty(date)) {
            cal.setTime(DateUtils.getNowDate());
        } else {
            cal.setTime(yearFormat.parse(date));
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;// 0周日
        GroupScheduleCycle groupSchCycle = groupScheduleCycleService.selectSchCycleByGroupId(groupId);
        Schedule schedule = new Schedule();
        if (w == 0) {// 周日
            schedule.setId(groupSchCycle.getSunday());
        } else if (w == 1) {// 周一
            schedule.setId(groupSchCycle.getMonday());
        } else if (w == 2) {// 周二
            schedule.setId(groupSchCycle.getTuesday());
        } else if (w == 3) {// 周三
            schedule.setId(groupSchCycle.getWednesday());
        } else if (w == 4) {// 周四
            schedule.setId(groupSchCycle.getThursday());
        } else if (w == 5) {// 周五
            schedule.setId(groupSchCycle.getFriday());
        } else if (w == 6) {// 周六
            schedule.setId(groupSchCycle.getSaturday());
        }
        // 当天的考勤规则
        schedule = scheduleService.selectOneObject(schedule);
        return schedule;
    }

    /**
     * 根据条件查询考勤
     *
     * @param params
     * @return
     */
    public Map<String, Object> getCheckWorkAttendance(Map<String, Object> params) {
        System.out.println();
        Map<String, Object> map = new HashMap<String, Object>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date date;
        Calendar cai = Calendar.getInstance();
        Calendar caj = Calendar.getInstance();
        try {
            RequestUtils.transformArray(params, "ids");
//            PageUtils.startPage(params);
            String month = (String) params.get("month");
            date = sdf.parse(month);
            params.put("workTime", month);
            String deptstr = (String) params.get("deptids");
            if (deptstr != null && !deptstr.equals("")) {
                String[] deptids = deptstr.split(",");
                params.put("deptids", deptids);
            }
            List<Attendance> monthRecord = baseMapper.selectCheckWorkAttendance(params);
//            PageUtils.responePage(map, monthRecord);
            map.put("monthRecord", monthRecord);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return map;
    }

    //获取当天的考勤班次
    public List<Map<String, Object>> getUserVeryDaySchedule() throws Exception {
        User user = LoginUtils.getCurrentUserInfo();
        String deptid = LoginUtils.getCurrentUserInfo().getDeptid();
        user.setDeptid(deptid);
        List<Map<String, Object>> scheduleArr = new ArrayList<>();
        //查询用户当天的考勤情况
        Attendance attendance = new Attendance();
        attendance.setUserid(user.getUserid());
        attendance.setWorkTime(new Date());
        List<Attendance> attendances = baseMapper.selectDayAttendance(attendance);
        Map<String, Attendance> attendanceMap = new HashMap<>();
        for (Attendance value : attendances) {
            attendanceMap.put(value.getScheduleTime(), value);
        }
        // 查询用户所属组别
        Group group = groupService.selectGroupByUseridAndDeptid(user.getUserid(), user.getDeptid());
        if (group != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            //查询当天考勤班次
            Schedule schedule = this.getTodaySchCycleByGroupId(simpleDateFormat.format(new Date()), group.getId());

            //当天有考勤班次
            if (schedule != null) {
                //一天一次
                if (schedule.getScheduleType().equals("1")) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("beOnDuty", schedule.getWorkTimea()); // 上班打卡时间
                    map.put("offDuty", schedule.getReleaseTimea()); //下班打卡时间
                    map.put("beOnDutyState", "0"); //0上班打卡
                    map.put("offDutyState", "1"); //1下班打卡
                    map.put("beWorkTime", "");  //上班签到时间
                    map.put("offTime", "");    //下班签退时间
                    map.put("beStatus", "0");  //上班是否已经打卡 0-否 1-是
                    map.put("offStatus", "0");  //下班是否已经打卡
                    map.put("beOntimeState", "");  //上班打卡后的状态
                    map.put("offOntimeState", "");  //下班打卡后的状态
                    map.put("beBtnPoi", "0");  //上班按钮位置
                    map.put("offBtnPoi", "1"); //下班按钮位置
                    Attendance att1 = attendanceMap.get(schedule.getWorkTimea());
                    Attendance att2 = attendanceMap.get(schedule.getReleaseTimea());
                    if (att1 != null) {
                        map.put("beWorkTime", att1.getWorkTime());
                        map.put("beStatus", "1");
                        map.put("beOntimeState", att1.getOntimeState());
                    }
                    if (att2 != null) {
                        map.put("offTime", att2.getWorkTime());
                        map.put("offStatus", "1");
                        map.put("offOntimeState", att2.getOntimeState());
                    }
                    scheduleArr.add(map);
                }
                //一天两次
                if (schedule.getScheduleType().equals("2")) {
                    Map<String, Object> map1 = new HashMap<>();
                    map1.put("beOnDuty", schedule.getWorkTimea());
                    map1.put("offDuty", schedule.getReleaseTimea());
                    map1.put("beOnDutyState", "0");
                    map1.put("offDutyState", "1");
                    map1.put("beWorkTime", "");
                    map1.put("offTime", "");
                    map1.put("beStatus", "0");
                    map1.put("offStatus", "0");
                    map1.put("beOntimeState", "");
                    map1.put("offOntimeState", "");
                    map1.put("beBtnPoi", "0");
                    map1.put("offBtnPoi", "1");
                    Map<String, Object> map2 = new HashMap<>();
                    map2.put("beOnDuty", schedule.getWorkTimeb());
                    map2.put("offDuty", schedule.getReleaseTimeb());
                    map2.put("beOnDutyState", "0");
                    map2.put("offDutyState", "1");
                    map2.put("beWorkTime", "");
                    map2.put("offTime", "");
                    map2.put("beStatus", "0");
                    map2.put("offStatus", "0");
                    map2.put("beOntimeState", "");
                    map2.put("offOntimeState", "");
                    map2.put("beBtnPoi", "2");
                    map2.put("offBtnPoi", "3");
                    Attendance att1 = attendanceMap.get(schedule.getWorkTimea());
                    Attendance att2 = attendanceMap.get(schedule.getReleaseTimea());
                    Attendance att3 = attendanceMap.get(schedule.getWorkTimeb());
                    Attendance att4 = attendanceMap.get(schedule.getReleaseTimeb());
                    if (att1 != null) {
                        map1.put("beWorkTime", att1.getWorkTime());
                        map1.put("beStatus", "1");
                        map1.put("beOntimeState", att1.getOntimeState());
                    }
                    if (att2 != null) {
                        map1.put("offTime", att2.getWorkTime());
                        map1.put("offStatus", "1");
                        map1.put("offOntimeState", att2.getOntimeState());
                    }
                    if (att3 != null) {
                        map2.put("beWorkTime", att3.getWorkTime());
                        map2.put("beStatus", "1");
                        map2.put("beOntimeState", att3.getOntimeState());
                    }
                    if (att4 != null) {
                        map2.put("offTime", att4.getWorkTime());
                        map2.put("offStatus", "1");
                        map2.put("offOntimeState", att4.getOntimeState());
                    }

                    scheduleArr.add(map1);
                    scheduleArr.add(map2);
                }
                //一天三次
                if (schedule.getScheduleType().equals("3")) {
                    Map<String, Object> map1 = new HashMap<>();
                    map1.put("beOnDuty", schedule.getWorkTimea());
                    map1.put("offDuty", schedule.getReleaseTimea());
                    map1.put("beOnDutyState", "0");
                    map1.put("offDutyState", "1");
                    map1.put("beWorkTime", "");
                    map1.put("offTime", "");
                    map1.put("beStatus", "0");
                    map1.put("offStatus", "0");
                    map1.put("beOntimeState", "");
                    map1.put("offOntimeState", "");
                    map1.put("beBtnPoi", "0");
                    map1.put("offBtnPoi", "1");
                    Map<String, Object> map2 = new HashMap<>();
                    map2.put("beOnDuty", schedule.getWorkTimeb());
                    map2.put("offDuty", schedule.getReleaseTimeb());
                    map2.put("beOnDutyState", "0");
                    map2.put("offDutyState", "1");
                    map2.put("beWorkTime", "");
                    map2.put("offTime", "");
                    map2.put("beStatus", "0");
                    map2.put("offStatus", "0");
                    map2.put("beOntimeState", "");
                    map2.put("offOntimeState", "");
                    map2.put("beBtnPoi", "2");
                    map2.put("offBtnPoi", "3");
                    Map<String, Object> map3 = new HashMap<>();
                    map3.put("beOnDuty", schedule.getWorkTimeb());
                    map3.put("offDuty", schedule.getReleaseTimeb());
                    map3.put("beOnDutyState", "0");
                    map3.put("offDutyState", "1");
                    map3.put("beWorkTime", "");
                    map3.put("offTime", "");
                    map3.put("beStatus", "0");
                    map3.put("offStatus", "0");
                    map3.put("beOntimeState", "");
                    map3.put("offOntimeState", "");
                    map3.put("beBtnPoi", "4");
                    map3.put("offBtnPoi", "5");
                    Attendance att1 = attendanceMap.get(schedule.getWorkTimea());
                    Attendance att2 = attendanceMap.get(schedule.getReleaseTimea());
                    Attendance att3 = attendanceMap.get(schedule.getWorkTimeb());
                    Attendance att4 = attendanceMap.get(schedule.getReleaseTimeb());
                    Attendance att5 = attendanceMap.get(schedule.getWorkTimec());
                    Attendance att6 = attendanceMap.get(schedule.getReleaseTimec());

                    if (att1 != null) {
                        map1.put("beWorkTime", att1.getWorkTime());
                        map1.put("beStatus", "1");
                        map1.put("beOntimeState", att1.getOntimeState());
                    }
                    if (att2 != null) {
                        map1.put("offTime", att2.getWorkTime());
                        map1.put("offStatus", "1");
                        map1.put("offOntimeState", att2.getOntimeState());
                    }
                    if (att3 != null) {
                        map2.put("beWorkTime", att3.getWorkTime());
                        map2.put("beStatus", "1");
                        map2.put("beOntimeState", att3.getOntimeState());
                    }
                    if (att4 != null) {
                        map2.put("offTime", att4.getWorkTime());
                        map2.put("offStatus", "1");
                        map2.put("offOntimeState", att4.getOntimeState());
                    }
                    if (att5 != null) {
                        map3.put("beWorkTime", att5.getWorkTime());
                        map3.put("beStatus", "1");
                        map3.put("beOntimeState", att5.getOntimeState());
                    }
                    if (att6 != null) {
                        map3.put("offTime", att6.getWorkTime());
                        map3.put("offStatus", "1");
                        map3.put("offOntimeState", att6.getOntimeState());
                    }

                    scheduleArr.add(map1);
                    scheduleArr.add(map2);
                    scheduleArr.add(map3);
                }

            }
        } else {
            //没加入考勤组默认九点上班7点下班，一天打卡一次
            //一天一次
            Map<String, Object> map = new HashMap<>();
            map.put("beOnDuty", "09:00");
            map.put("offDuty", "19:00");
            map.put("beOnDutyState", "0");
            map.put("offDutyState", "1");
            map.put("beWorkTime", "");
            map.put("offTime", "");
            map.put("beStatus", "0");
            map.put("offStatus", "0");
            map.put("beOntimeState", "");
            map.put("offOntimeState", "");
            map.put("beBtnPoi", "0");
            map.put("offBtnPoi", "1");
            Attendance att1 = attendanceMap.get("09:00");
            Attendance att2 = attendanceMap.get("19:00");
            if (att1 != null) {
                map.put("beWorkTime", att1.getWorkTime());
                map.put("beStatus", "1");
                map.put("beOntimeState", att1.getOntimeState());
            }
            if (att2 != null) {
                map.put("offTime", att2.getWorkTime());
                map.put("offStatus", "1");
                map.put("offOntimeState", att2.getOntimeState());
            }
            scheduleArr.add(map);
        }

        return scheduleArr;
    }
}

